package com.kanq.service.designpatterns.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author cheng jun
 * @Description: 代理模式:动态代理----------------AOP
 * @Date 2021/7/14 21:37
 */
public class People2 implements PeopleInterface2 {
    @Override
    public void move() {
        System.out.println("走路------------------");
    }

    public static void main(String[] args) {
        People2 people2 = new People2();

        /*PeopleInterface2 peopleInterface2 = (PeopleInterface2) Proxy.newProxyInstance(
                People2.class.getClassLoader(),
                new Class[]{PeopleInterface2.class},
                new LogsHander(new People2())
                );
        peopleInterface2.move();*/

        PeopleInterface2 peopleInterface2 = (PeopleInterface2) Proxy.newProxyInstance(
                People2.class.getClassLoader(),
                new Class[]{PeopleInterface2.class},
                (proxy, method, args1) -> {
                    System.out.println("logs start-------------------------" + method.getName());
                    Object o = method.invoke(people2, args1);
                    System.out.println("logs end---------------------------" + method.getName());
                    return o;
                });
        peopleInterface2.move();
    }
}

class LogsHander implements InvocationHandler {

    People2 people2;

    public LogsHander(People2 people2) {
        this.people2 = people2;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        System.out.println("logs start-------------------------" + method.getName());
        Object o = method.invoke(people2, args);
        System.out.println("logs end---------------------------" + method.getName());
        return o;
    }
}

interface PeopleInterface2 {
    void move();
}
